package com.txc.books.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.txc.books.mapper.BookMapper;
import com.txc.books.entity.Book;
import com.txc.books.service.IBookService;
import com.txc.books.utils.PageRequest;
import com.txc.books.utils.PageResult;
import com.txc.books.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: XCTANG
 */


@Service
public class BookServiceImpl implements IBookService {

    private final BookMapper bookMapper;

    public BookServiceImpl(BookMapper bookMapper){
        this.bookMapper = bookMapper;
    }

    @Override
    public List<Book> findAll() {
        return bookMapper.findAll();
    }

    @Override
    public void insert(Book book) {
        String name = book.getName();
        String author = book.getAuthor();

        if (StringUtils.isEmpty(name)){
            throw new IllegalArgumentException("名字不能为空");
        }
        if (StringUtils.isBlank(name)){
            throw new IllegalArgumentException("名字不能为空白");
        }
        if (StringUtils.isEmpty(author)){
            throw new IllegalArgumentException("作者不能为空");
        }
        if (StringUtils.isBlank(author)){
            throw new IllegalArgumentException("作者不能为空白");
        }
        bookMapper.insert(book);
    }

    @Override
    public void update(Book book) {
        String name = book.getName();
        String author = book.getAuthor();

        if (StringUtils.isEmpty(name)){
            throw new IllegalArgumentException("名字不能为空");
        }
        if (StringUtils.isBlank(name)){
            throw new IllegalArgumentException("名字不能为空白");
        }
        if (StringUtils.isEmpty(author)){
            throw new IllegalArgumentException("作者不能为空");
        }
        if (StringUtils.isBlank(author)){
            throw new IllegalArgumentException("作者不能为空白");
        }
        bookMapper.update(book);
    }

    @Override
    public void delete(Integer id) {
        bookMapper.delete(id);
    }

    @Override
    public void select(Integer id) {
        bookMapper.select(id);
    }

    @Override
    public PageResult findByPager(PageRequest pageRequest) {
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    public PageInfo<Book> getPageInfo(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Book> bookMenus = bookMapper.selectPage();
        return new PageInfo<Book>(bookMenus);
    }
}
